package it.polito.let.http;

import java.io.*;
import java.net.*;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

public class Server {

	public static void main(String args[]) {

		Logger.getLogger("it.polito.let.jhpserver").addHandler(new Handler() {

			@Override
			public void close() throws SecurityException {

			}

			@Override
			public void flush() {

			}

			@Override
			public void publish(LogRecord record) {

				System.err.println(record.toString());

			}

		});
		Logger.getLogger("it.polito.let.jhpserver").setLevel(Level.ALL);
		int port = HTTPConstants.HTTP_PORT;
		if (args.length > 0) {
			try {
				port = Integer.parseInt(args[0]);
			} catch (NumberFormatException e) {
				port = HTTPConstants.HTTP_PORT;
			}
		}
		try {
			// crea e connette la socket
			ServerSocket so = new ServerSocket(port,HTTPConstants.MAX_REQ);
			Logger.getLogger("it.polito.let.jhpserver").info("HTTP Server: inizializzato sulla porta "+ so.getLocalPort());

			while (true) {
				// si mette in ascolto
				Socket newso = so.accept();

				Logger.getLogger("it.polito.let.jhpserver").info(
						"HTTP Server: request from "
						+ newso.getInetAddress().toString());
				// esegue un thread in modo parallelo
				new ClientHandler(newso).start();
				Logger.getLogger("it.polito.let.jhpserver").info(
				"HTTP Server: child thread spawned");
			}

		}
		catch (IOException e) {
			Logger.getLogger("it.polito.let.jhpserver").severe(
					"Main thread exception: " + e.getMessage());
		}
	}
} // class ServerHTTP
